class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
        int cnt=1;
        int dx[]={0,1,0,-1};
        int dy[]={1,0,-1,0};
        int i=0;
        int j=0;
        int index=0;
        vector<vector<int>>dp(n,vector<int>(n));
        while(cnt<=n*n)
        {
            dp[i][j]=cnt;
            cnt++;

            int a=i+dx[index];int b=j+dy[index];
            if(!(a>=0&&a<n&&b>=0&&b<n)||dp[a][b]!=0)
            {
                index=(index+1)%4;
                //更新坐标
                a=i+dx[index];
                b=j+dy[index];
            }
            i=a;
            j=b;
        }
        return dp;
    }
};
